import 'bootstrap-validator';
import { post } from 'utils/request';
import { make_formdata } from 'utils';

const $form = $('#myForm');
const $btn = $form.find('#submit');
const $result = $('#result');
const $imgInput = $form.find('.imgbox>input');
const $imgThumb = $form.find('.imgbox>img');

$form.validator().on('submit', function (e) {
  if (e.isDefaultPrevented()) {
    console.log('表单验证不通过');
  } else {
    e.preventDefault();

    $('#result').val('稍等...');

    let post_data = make_formdata({
      model: this.model.value,
      image: this.iamge.files[0],
    });

    $btn.button('loading');
    post({
      processData: false,
      contentType: false,
      url: 'ai/fruit',
      data: post_data,
    }).done(d => {
      $result.val(d);
    }).fail(d => {
      $result.val(d.toString());
    }).always(() => {
      $btn.button('reset');
    });
  }
});

$imgInput.on('change', function (e) {
  let file = this.files[0];
  let src = file ? URL.createObjectURL(file) : '';
  $imgThumb.attr('src', src);
});